package com.huawei.mylibrary.dialog;


import com.huawei.mylibrary.ResourceTable;
import com.huawei.mylibrary.callback.FingerprintCallback;
import com.huawei.mylibrary.callback.FingerprintDialogCallback;
import com.huawei.mylibrary.callback.FingerprintDialogSecureCallback;
import com.huawei.mylibrary.callback.FingerprintSecureCallback;
import com.huawei.mylibrary.utils.FingerprintToken;
import com.huawei.mylibrary.view.Fingerprint;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.TextField;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.global.resource.Element;


public class FingerprintDialog extends AnimatedDialog<FingerprintDialog> {

    private Fingerprint fingerprint;
    private TextField dialogTitle, dialogMessage, dialogStatus;
    private Button cancelButton, usePasswordButton;
    private FingerprintDialogCallback fingerprintDialogCallback;
    private FingerprintDialogSecureCallback fingerprintDialogSecureCallback;
    private int statusScanningColor, statusSuccessColor, statusErrorColor;
    private Component.ClickedListener onUsePassword;
    private EventHandler handler;
    private int delayAfterError, delayAfterSuccess;

    private final static String TAG = "FingerprintDialog";

    public FingerprintDialog(Context context) {
        super(context);
    }

    private void init() {
        this.handler = new EventHandler(EventRunner.getMainEventRunner());
        this.onUsePassword = null;
        this.delayAfterError = Fingerprint.DEFAULT_DELAY_AFTER_ERROR;
        this.delayAfterSuccess = Fingerprint.DEFAULT_DELAY_AFTER_ERROR;

        this.statusScanningColor = ResourceTable.String_status_scanning;
        this.statusSuccessColor = ResourceTable.String_status_success;
        this.statusErrorColor = ResourceTable.String_status_error;

        this.dialogComponent = layoutScatter.parse(ResourceTable.Layout_fingerprint_dialog, null, false);
        this.fingerprint = (Fingerprint) dialogComponent.findComponentById(ResourceTable.Id_fingerprint_dialog_fp);
        this.dialogTitle = (TextField) dialogComponent.findComponentById(ResourceTable.Id_fingerprint_dialog_title);
        this.dialogMessage = (TextField) dialogComponent.findComponentById(ResourceTable.Id_fingerprint_dialog_message);
        this.dialogStatus = (TextField) dialogComponent.findComponentById(ResourceTable.Id_fingerprint_dialog_status);
        this.cancelButton = (Button) dialogComponent.findComponentById(ResourceTable.Id_fingerprint_dialog_cancel);
        this.usePasswordButton = (Button) dialogComponent.findComponentById(ResourceTable.Id_fingerprint_dialog_use_password);
    }


    private void authenticate() {
        fingerprint.authenticate();
    }

    private void setStatus(int textId, int textColorId) {
        setStatus(context.getString(textId), textColorId);
    }

    private void setStatus(String text, int textColorId) {
        //TODO 系统颜色获取
//        dialogStatus.setTextColor(ResourcesCompat.getColor(context.getResources(), textColorId, context.getTheme()));
        dialogStatus.setTextColor(new Color(ResourceTable.String_dialog_status));
        dialogStatus.setText(text);
    }

    private Runnable returnToScanning = new Runnable() {
        @Override
        public void run() {
            setStatus(ResourceTable.String_fingerprint_state_scanning, statusScanningColor);
        }
    };

    private FingerprintCallback fingerprintCallback = new FingerprintCallback() {
        @Override
        public void onAuthenticationSucceeded() {
            handler.removeTask(returnToScanning);
            setStatus(ResourceTable.String_fingerprint_state_success, statusSuccessColor);
            handler.postTask(new Runnable() {
                @Override
                public void run() {
                    dialog.remove();
                    if (fingerprintDialogCallback != null) {
                        fingerprintDialogCallback.onAuthenticationSucceeded();
                    }
                }
            }, delayAfterSuccess);
        }

        @Override
        public void onAuthenticationFailed() {
            setStatus(ResourceTable.String_fingerprint_state_failure, statusErrorColor);
            handler.postTask(returnToScanning, delayAfterError);
        }

        @Override
        public void onAuthenticationError(int errorCode, String error) {
            setStatus(error, statusErrorColor);
            handler.postTask(returnToScanning, delayAfterError);
        }
    };

    private FingerprintSecureCallback fingerprintSecureCallback = new FingerprintSecureCallback() {
        @Override
        public void onAuthenticationSucceeded() {
            handler.removeTask(returnToScanning);
            setStatus(ResourceTable.String_fingerprint_state_success, statusSuccessColor);
            handler.postTask(new Runnable() {
                @Override
                public void run() {
                    dialog.remove();
                    if(fingerprintDialogSecureCallback!=null){
                        fingerprintDialogSecureCallback.onAuthenticationSucceeded();
                    }
                }
            }, delayAfterSuccess);
        }

        @Override
        public void onAuthenticationFailed() {
            setStatus(ResourceTable.String_fingerprint_state_failure, statusErrorColor);
            handler.postTask(returnToScanning, delayAfterError);
        }

        @Override
        public void onNewFingerprintEnrolled(FingerprintToken token) {
            dialog.remove();
            if(fingerprintDialogSecureCallback!=null){
                fingerprintDialogSecureCallback.onNewFingerprintEnrolled(token);
            }
        }

        @Override
        public void onAuthenticationError(int errorCode, String error) {
            setStatus(error, statusErrorColor);
            handler.postTask(returnToScanning, delayAfterError);
        }
    };


    /**
     * Check if a fingerprint scanner is available and if at least one finger is enrolled in the phone.
     *
     * @param context A context
     * @return True is authentication is available, False otherwise
     */
    public static boolean isAvailable(Context context) {
//        FingerprintManager manager = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
//        return (manager!=null && manager.isHardwareDetected() && manager.hasEnrolledFingerprints());
        return true;
    }

    /**
     * Create a FingerprintDialog instance.
     *
     * @param context Activity Context
     * @return FingerprintDialog instance
     */
    public static FingerprintDialog initialize(Context context) {
        return new FingerprintDialog(context);
    }

    /**
     * Set an authentication callback.
     *
     * @param fingerprintDialogCallback The callback
     * @return FingerprintDialog object
     */
    public FingerprintDialog callback(FingerprintDialogCallback fingerprintDialogCallback) {
        this.fingerprintDialogCallback = fingerprintDialogCallback;
        this.fingerprint.callback(fingerprintCallback);
        return this;
    }

    /**
     * Set a callback for secured authentication.
     * @param fingerprintDialogSecureCallback The callback
     * @param KEY_NAME An arbitrary string used to create a cipher pair in the Android KeyStore
     * @return FingerprintDialog object
     */
    public FingerprintDialog callback(FingerprintDialogSecureCallback fingerprintDialogSecureCallback, String KEY_NAME){
        this.fingerprintDialogSecureCallback = fingerprintDialogSecureCallback;
        this.fingerprint.callback(fingerprintSecureCallback,KEY_NAME);
        return this;
    }

    /**
     * Perform a secured authentication using that particular CryptoObject.
     * @param cryptoObject CryptoObject to use
     * @return FingerprintDialog object
     */
//    TODO FingerprintManager
//    public FingerprintDialog cryptoObject(FingerprintManager.CryptoObject cryptoObject){
//        this.fingerprint.cryptoObject(cryptoObject);
//        return this;
//    }

    /**
     * Set color of the fingerprint scanning status.
     * @param fingerprintScanningColor resource color
     * @return FingerprintDialog object
     */
    public FingerprintDialog fingerprintScanningColor(int fingerprintScanningColor){
        this.fingerprint.fingerprintScanningColor(fingerprintScanningColor);
        return this;
    }

    /**
     * Set color of the fingerprint success status.
     * @param fingerprintSuccessColor resource color
     * @return FingerprintDialog object
     */
    public FingerprintDialog fingerprintSuccessColor(int fingerprintSuccessColor){
        this.fingerprint.fingerprintSuccessColor(fingerprintSuccessColor);
        return this;
    }

    /**
     * Set color of the fingerprint error status.
     * @param fingerprintErrorColor resource color
     * @return FingerprintDialog object
     */
    public FingerprintDialog fingerprintErrorColor(int fingerprintErrorColor){
        this.fingerprint.fingerprintErrorColor(fingerprintErrorColor);
        return this;
    }

    /**
     * Set color of the circle scanning status.
     * @param circleScanningColor resource color
     * @return FingerprintDialog object
     */
    public FingerprintDialog circleScanningColor(int circleScanningColor){
        this.fingerprint.circleScanningColor(circleScanningColor);
        return this;
    }

    /**
     * Set color of the circle success status.
     * @param circleSuccessColor resource color
     * @return FingerprintDialog object
     */
    public FingerprintDialog circleSuccessColor(int circleSuccessColor){
        this.fingerprint.circleSuccessColor(circleSuccessColor);
        return this;
    }

    /**
     * Set color of the circle error status.
     * @param circleErrorColor resource color
     * @return FingerprintDialog object
     */
    public FingerprintDialog circleErrorColor(int circleErrorColor){
        this.fingerprint.circleErrorColor(circleErrorColor);
        return this;
    }


}
